package com.example.androidcomplete02.parser;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.widget.ListView;

import com.example.androidcomplete02.R;

public class Json_parserAcitivity extends Activity {
	ListView list;
	ProgressDialog progressDlg;

	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.ch28_network_xmlparser);
		list = (ListView) findViewById(R.id.listView);
		new ParsingXml().execute("order.json");
	}

	private class ParsingXml extends AsyncTask<String, Void, ArrayList<Item>> {
		protected void onPreExecute() {
			progressDlg = ProgressDialog.show(Json_parserAcitivity.this,
					"Wait", "xml parsing ...");
		}

		protected void onPostExecute(ArrayList<Item> result) {
			MyAdapter adapter = new MyAdapter(Json_parserAcitivity.this, result);
			progressDlg.dismiss();
			list.setAdapter(adapter);
		}

		protected ArrayList<Item> doInBackground(String... params) {
			StringBuilder sb = new StringBuilder();
			String str = null;

			try {
				BufferedReader br = new BufferedReader(new InputStreamReader(
						openFileInput(params[0])));
				while ((str = br.readLine()) != null) {
					sb.append(str);
				}
				br.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
			return parsingXml(sb.toString());
		}
	}

	public ArrayList<Item> parsingXml(String xml) {
		ArrayList<Item> arItem = new ArrayList<Item>();
		Item itemClass;
		try {
			JSONArray ja = new JSONArray(xml);
			for (int i = 0; i < ja.length(); i++) {
				JSONObject order = ja.getJSONObject(i);
				itemClass = new Item();
				itemClass.setItemName(order.getString("Product"));
				itemClass.setMakerName(order.getString("Maker"));
				itemClass.setItemPrice(order.getInt("Price"));
				arItem.add(itemClass);
			}
		} catch (JSONException e) {
			e.printStackTrace();
		}
		return arItem;
	}
}